import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:syn_4s/core/constants/event_code.dart';
import 'package:syn_4s/core/extension/build_context_extension.dart';
import 'package:syn_4s/core/services/tag_request.dart';
import 'package:syn_4s/core/utils/dialog_utils.dart';
import 'package:syn_4s/core/utils/toast_utils.dart';

import '../constants/sp_key.dart';
import '../constants/tag_code.dart';
import '../services/config.dart';
import '../utils/event_bus.dart';
import 'language_view_model.dart';

class ChangeLanguageViewModel extends GetxController {
  var language = "".obs;
  int? languageId;

  init(BuildContext context) {
    SharedPreferences.getInstance().then((value) {
      languageId = value.getInt(keyLanguage) ?? 1;
      setLanguageValue();
    });
  }

  changeLanguageValue(String? code) {
    if (code == null) {
      return;
    }
    int newLang = int.parse(code);
    if (newLang == languageId) {
      return;
    }
    languageId = newLang;
    setLanguageValue();
  }

  setLanguageValue() {
    language.value = languageId == 1 ? "中文" : "English";
  }

  save(BuildContext context) {
    SharedPreferences.getInstance().then((sp) {
      int oldLanguageId = sp.getInt(keyLanguage) ?? 1;
      if (languageId == oldLanguageId) {
        ToastUtils.showToast(context.l10n.save);
        Navigator.pop(context);
        return;
      }
      DialogUtils.loading(context);
      sp.setInt(keyLanguage, languageId ?? 1);
      TagRequest.getTags().then((value) {
        DialogUtils.closeDialog(context);
        if (value.status != HttpConfig.success) {
          sp.setInt(keyLanguage, oldLanguageId);
          ToastUtils.showToast(value.message ?? "");
          return;
        }
        Intl.defaultLocale = languageId == 1 ? "zh" : "en";
        String? codes = value.data
            ?.tags?.map((tag) => tag.code)
            .where((code) =>
                code != null &&
                code.isNotEmpty &&
                code != codeStatus &&
                code != codeRealLocation &&
                code != codeTowerCrane &&
                code != codeSurveillance)
            .join(',');
        sp.setString(keyTagCode, codes ?? "");
        sp.setString(
            keyTag, jsonEncode(value.data?.tags?.map((v) => v.toJson()).toList()));
        ToastUtils.showToast(context.l10n.save);
        Navigator.pop(context);
        Get.find<LanguageViewModel>().changeLocale(languageId);
        eventBus.fire(eventLanguage);
      }).catchError((err) {
        sp.setInt(keyLanguage, oldLanguageId);
        DialogUtils.closeDialog(context);
        ToastUtils.showNetError(context);
      });
    });
  }
}
